package com.example.leetdemo.finash;

public class Solution875 {


    public int minEatingSpeed(int[] piles, int h) {
        int begin = 1, end = 0;
        for (int i = 0; i < piles.length; i++) {
            end = Math.max(end, piles[i]);
        }
        int middle = 0;
        while (true) {
            middle = (end - begin) / 2 + begin;
            if (check(middle, piles, h)) {
                end = middle;
            } else {
                begin = middle + 1;
            }
            if (begin == end || begin > end) {
                break;
            }
        }
        return begin;
    }

    private boolean check(int middle, int[] piles, int h) {
        int size = 0;
        for (int i = 0; i < piles.length; i++) {
            if (piles[i] % middle > 0) {
                size += piles[i] / middle + 1;
            } else {
                size += piles[i] / middle;
            }
            if (size > h) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution875 solution875 = new Solution875();
        System.err.println(solution875.minEatingSpeed(new int[] {3,6,7,11}, 8));
    }
}
